import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons'
import { uniqueId } from 'lodash-es'
import { useEffect, useState } from 'react'

import {
  createNursingItemApi,
  getNursingItemDetailApi,
  nursingTypeListApi,
  updateNursingItemApi,
} from '@/api/pcs/pcsNursingItem'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import { PCS_ATTRIBUTE_TYPE_ENUM, PCS_DEFAULT_CHECKED_IN_NURSING_PLAN_ENUM } from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

const EditModal = ({ row = {} }) => {
  const [form] = AekForm.useForm()
  const displayInLifeLog = AekForm.useWatch('displayInLifeLog', form)
  const attribute = AekForm.useWatch('attribute', form)
  const { id } = row
  const [options, setOptions] = useState([{ key: uniqueId() }])

  const getDetail = async () => {
    const { data } = await requestWithTry(getNursingItemDetailApi, {
      id,
    })
    const optionMap = {}
    if (data.optionList) {
      const options = data.optionList.map(option => {
        const key = uniqueId()
        optionMap[key] = option.value
        return {
          key,
          value: option.value,
        }
      })
      setOptions(options)
    }
    form.setFieldsValue({
      ...data,
      optionMap,
    })
  }

  useEffect(() => {
    if (!id) return
    getDetail()
  }, [id])

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      field: 'nursingItemName',
      label: '护嘱事项',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'Input' },
    },
    {
      field: 'nursingTypeId',
      label: '护嘱分类',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekSelect',
        props: {
          api: nursingTypeListApi,
          fieldNames: {
            value: 'id',
            label: 'nursingTypeName',
          },
        },
      },
    },
    {
      field: 'nursingItemContent',
      label: '内容',
      component: { name: 'AekTextArea' },
    },
    {
      field: 'attribute',
      label: '属性',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Select',
        props: {
          options: PCS_ATTRIBUTE_TYPE_ENUM.options,
        },
      },
      other: attribute === PCS_ATTRIBUTE_TYPE_ENUM.RADIO && (
        <PlusCircleOutlined
          className='c-primary'
          onClick={() => {
            setOptions([...options, { key: uniqueId() }])
          }}
        />
      ),
    },
    ...options.map(
      (item, index) =>
        /**@type {import("@/components/AekForm").FormDataProps} */
        ({
          exclude: attribute !== PCS_ATTRIBUTE_TYPE_ENUM.RADIO,
          field: ['optionMap', item.key],
          label: `选项${index + 1}`,
          layout: ['120px'],
          component: { name: 'Input' },
          formItemProps: {
            rules: [{ required: true }],
          },
          other: (
            <>
              {options.length > 1 && (
                <MinusCircleOutlined
                  className='c-del'
                  onClick={() => {
                    setOptions(options.filter(options => options.key !== item.key))
                  }}
                />
              )}
            </>
          ),
        }),
    ),
    {
      exclude: attribute !== PCS_ATTRIBUTE_TYPE_ENUM.NUMBER,
      field: 'unit',
      label: '单位',
      layout: ['120px'],
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'Input' },
    },
    {
      field: 'defaultCheckedInNursingPlan',
      label: '护嘱计划',
      formItemProps: {
        valuePropName: 'checked',
      },
      component: {
        name: 'Checkbox',
        props: {
          children: PCS_DEFAULT_CHECKED_IN_NURSING_PLAN_ENUM.getText(1),
        },
      },
    },
    {
      field: 'displayInLifeLog',
      label: '生活日志',
      formItemProps: {
        valuePropName: 'checked',
      },
      component: {
        name: 'Checkbox',
        props: {
          children: '启用',
        },
      },
    },
    {
      exclude: !displayInLifeLog,
      field: 'lifeLogWeight',
      label: '权重',
      component: { name: 'InputNumber', props: { placeholder: '1-999', min: 1, max: 999 } },
    },
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    let sortedKeys = []
    if (values.optionMap) {
      sortedKeys = Object.keys(values.optionMap)
        .map(Number)
        .sort((a, b) => a - b)
    }
    let sortedArray = []
    if (sortedKeys?.length) {
      sortedArray = sortedKeys.map(key => ({
        value: values.optionMap[key],
        label: values.optionMap[key],
      }))
    }
    const params = {
      id,
      ...values,
      lifeLogWeight: values.lifeLogWeight || 0,
      defaultCheckedInNursingPlan: values.defaultCheckedInNursingPlan ? 1 : 0,
      displayInLifeLog: values.displayInLifeLog ? 1 : 0,
      optionList: sortedArray,
    }
    await requestWithTry(id ? updateNursingItemApi : createNursingItemApi, params)
  }
  return (
    <AekModal title={id ? '编辑' : '新增'} width={500} onOk={onOk}>
      <AekForm form={form} formData={formData} />
    </AekModal>
  )
}

EditModal.PromiseThen = PromiseThen

export default EditModal
